import org.junit.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Test01 {

//    插入数据
    @Test
    public void insert() {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            JDBCUtiles.loadDriver();    // 注册驱动
            connection = JDBCUtiles.connection();   //　建立连接

            String sql = "insert into crud value (?,?,?)";  // 编写SQL语句
            statement = connection.prepareStatement(sql);   // 预编译SQL语句
//            给SQL语句赋值
            statement.setInt(1,1);  // 整数赋值
            statement.setString(2,"nick");  // 字符串赋值
            statement.setInt(3,23);

            int num = statement.executeUpdate();    // 执行SQL
            if (num > 0) {
                System.out.println("保存成功");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
//            关闭资源
            JDBCUtiles.close(connection,statement);
        }
    }

//    查询数据
    @Test
    public void query() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            JDBCUtiles.loadDriver();    // 注册驱动
            connection = JDBCUtiles.connection();   //　建立连接

            String sql = "select * from crud";  // 编写SQL语句
            statement = connection.prepareStatement(sql);   // 预编译SQL语句

            resultSet = statement.executeQuery();  // 执行SQL

            while (resultSet.next()) {
                System.out.println("id:"+resultSet.getInt("id")+", name:"+resultSet.getString("name")+" ,age:"+resultSet.getInt("age"));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
//            关闭资源
            JDBCUtiles.queryClose(connection,statement,resultSet);
        }
    }
}
